/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import entities.Institution;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Country;
import entities.User;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author santiagobaldrich
 */
public class InstitutionJpaController {

    public InstitutionJpaController()
    {
        emf = Persistence.createEntityManagerFactory("UNOJModelPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(Institution institution)
    {
        if (institution.getUserCollection() == null)
        {
            institution.setUserCollection(new ArrayList<User>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Country country = institution.getCountry();
            if (country != null)
            {
                country = em.getReference(country.getClass(), country.getIdCountry());
                institution.setCountry(country);
            }
            Collection<User> attachedUserCollection = new ArrayList<User>();
            for (User userCollectionUserToAttach : institution.getUserCollection())
            {
                userCollectionUserToAttach = em.getReference(userCollectionUserToAttach.getClass(), userCollectionUserToAttach.getIdUser());
                attachedUserCollection.add(userCollectionUserToAttach);
            }
            institution.setUserCollection(attachedUserCollection);
            em.persist(institution);
            if (country != null)
            {
                country.getInstitutionCollection().add(institution);
                country = em.merge(country);
            }
            for (User userCollectionUser : institution.getUserCollection())
            {
                Institution oldInstitutionOfUserCollectionUser = userCollectionUser.getInstitution();
                userCollectionUser.setInstitution(institution);
                userCollectionUser = em.merge(userCollectionUser);
                if (oldInstitutionOfUserCollectionUser != null)
                {
                    oldInstitutionOfUserCollectionUser.getUserCollection().remove(userCollectionUser);
                    oldInstitutionOfUserCollectionUser = em.merge(oldInstitutionOfUserCollectionUser);
                }
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(Institution institution) throws IllegalOrphanException, NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Institution persistentInstitution = em.find(Institution.class, institution.getIdInstitution());
            Country countryOld = persistentInstitution.getCountry();
            Country countryNew = institution.getCountry();
            Collection<User> userCollectionOld = persistentInstitution.getUserCollection();
            Collection<User> userCollectionNew = institution.getUserCollection();
            List<String> illegalOrphanMessages = null;
            for (User userCollectionOldUser : userCollectionOld)
            {
                if (!userCollectionNew.contains(userCollectionOldUser))
                {
                    if (illegalOrphanMessages == null)
                    {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain User " + userCollectionOldUser + " since its institution field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (countryNew != null)
            {
                countryNew = em.getReference(countryNew.getClass(), countryNew.getIdCountry());
                institution.setCountry(countryNew);
            }
            Collection<User> attachedUserCollectionNew = new ArrayList<User>();
            for (User userCollectionNewUserToAttach : userCollectionNew)
            {
                userCollectionNewUserToAttach = em.getReference(userCollectionNewUserToAttach.getClass(), userCollectionNewUserToAttach.getIdUser());
                attachedUserCollectionNew.add(userCollectionNewUserToAttach);
            }
            userCollectionNew = attachedUserCollectionNew;
            institution.setUserCollection(userCollectionNew);
            institution = em.merge(institution);
            if (countryOld != null && !countryOld.equals(countryNew))
            {
                countryOld.getInstitutionCollection().remove(institution);
                countryOld = em.merge(countryOld);
            }
            if (countryNew != null && !countryNew.equals(countryOld))
            {
                countryNew.getInstitutionCollection().add(institution);
                countryNew = em.merge(countryNew);
            }
            for (User userCollectionNewUser : userCollectionNew)
            {
                if (!userCollectionOld.contains(userCollectionNewUser))
                {
                    Institution oldInstitutionOfUserCollectionNewUser = userCollectionNewUser.getInstitution();
                    userCollectionNewUser.setInstitution(institution);
                    userCollectionNewUser = em.merge(userCollectionNewUser);
                    if (oldInstitutionOfUserCollectionNewUser != null && !oldInstitutionOfUserCollectionNewUser.equals(institution))
                    {
                        oldInstitutionOfUserCollectionNewUser.getUserCollection().remove(userCollectionNewUser);
                        oldInstitutionOfUserCollectionNewUser = em.merge(oldInstitutionOfUserCollectionNewUser);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = institution.getIdInstitution();
                if (findInstitution(id) == null)
                {
                    throw new NonexistentEntityException("The institution with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Institution institution;
            try
            {
                institution = em.getReference(Institution.class, id);
                institution.getIdInstitution();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The institution with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<User> userCollectionOrphanCheck = institution.getUserCollection();
            for (User userCollectionOrphanCheckUser : userCollectionOrphanCheck)
            {
                if (illegalOrphanMessages == null)
                {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Institution (" + institution + ") cannot be destroyed since the User " + userCollectionOrphanCheckUser + " in its userCollection field has a non-nullable institution field.");
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Country country = institution.getCountry();
            if (country != null)
            {
                country.getInstitutionCollection().remove(institution);
                country = em.merge(country);
            }
            em.remove(institution);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<Institution> findInstitutionEntities()
    {
        return findInstitutionEntities(true, -1, -1);
    }

    public List<Institution> findInstitutionEntities(int maxResults, int firstResult)
    {
        return findInstitutionEntities(false, maxResults, firstResult);
    }

    private List<Institution> findInstitutionEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Institution.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public Institution findInstitution(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Institution.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getInstitutionCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Institution> rt = cq.from(Institution.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

    public Institution getInstitutionByName(String name)
    {
        EntityManager em = null;
        Institution c = null;
        try
        {
            em = getEntityManager();
            Query q = em.createNamedQuery("Institution.findByName");
            q.setParameter("name", name);
            c = (Institution) q.getSingleResult();
        } catch (Exception e)
        {
            c = null;
        } finally
        {
            em.close();
            return c;
        }
    }

    public List<Institution> findAll()
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            Query q = em.createNamedQuery("Institution.findAll");
            return (List<Institution>)q.getResultList();
        } catch (Exception e)
        {
            System.out.println("Exception at InstitutionJPAController.findAll: " +e.getMessage() );
            return null;
        }
    }
}
